import { Injectable } from '@nestjs/common';
import { UserEntity } from './entities/user.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Search } from 'src/common/decorators/search.decorator';

import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { ListUserReturn } from './dto/list-user.dto';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
  ) {}

  async create(createUserDto: CreateUserDto): Promise<UserEntity> {
    let userItem = this.userRepository.create(createUserDto);
    userItem = await this.userRepository.save(userItem);
    return await this.findOne(userItem.id);
  }

  async findAll({
    page,
    limit,
    pagesize,
    offset,
    order,
    where,
  }: Search): Promise<ListUserReturn> {
    const [rows, total] = await this.userRepository.findAndCount({
      relations: { role: true },
      where,
      order,
      take: limit,
      skip: offset,
      select: ['id', 'phone', 'email', 'username'],
    });

    return {
      total,
      rows,
      page,
      pagesize,
    };
  }

  async findOne(id: string): Promise<UserEntity> {
    const userItem = await this.userRepository.findOne({
      relations: { role: true },
      where: { id },
      select: ['id', 'phone', 'email', 'username'],
    });
    return userItem;
  }

  async update(id: string, updateUserDto: UpdateUserDto): Promise<string> {
    await this.userRepository.update(id, updateUserDto);
    return 'success';
  }

  async remove(id: string): Promise<string> {
    await this.userRepository.softDelete(id);
    return 'success';
  }
}
